/**
 * 初始化
 * npm install gulp
 * npm install gulp-util gulp-imagemin gulp-sass gulp-minify-css gulp-minify-html gulp-uglify gulp-rename gulp-concat gulp-clean gulp-clean tiny-lr --save-dev
 */

// 引入 gulp及组件
var gulp = require('gulp'),                 //基础库
    imagemin = require('gulp-imagemin'),       //图片压缩
    sass = require('gulp-ruby-sass'),          //sass
    minifycss = require('gulp-minify-css'),    //css压缩
    minifyhtml = require("gulp-minify-html"), //html压缩
    jshint = require('gulp-jshint'),           //js检查
    uglify = require('gulp-uglify'),          //js压缩
    rename = require('gulp-rename'),           //重命名
    concat = require('gulp-concat'),          //合并文件
    clean = require('gulp-clean'),             //清空文件夹
    tinylr = require('tiny-lr'),               //livereload
    server = tinylr(),
    port = 35729,
    livereload = require('gulp-livereload');   //livereload

// HTML处理
gulp.task('html', function () {
    var htmlSrc = './src/**/*.html',
        htmlDst = './dist/';
    gulp.src(htmlSrc)
        .pipe(minifyhtml())
        .pipe(livereload(server))
        .pipe(gulp.dest(htmlDst));
});

// 样式处理
gulp.task('css', function () {
    var cssSrc = './src/css/*.css',
        cssDst = './dist/css';
    gulp.src(cssSrc)
        .pipe(gulp.dest(cssDst))
        .pipe(minifycss())
        .pipe(livereload(server))
        .pipe(gulp.dest(cssDst));
});

// 图片处理
gulp.task('images', function () {
    var imgSrc = './src/images/**/*',
        imgDst = './dist/images';
    gulp.src(imgSrc)
        .pipe(imagemin())
        .pipe(livereload(server))
        .pipe(gulp.dest(imgDst));
})

// js处理
gulp.task('js', function () {
    var appSrc = './src/**/*.js',
        appDst = './dist/';
    gulp.src(appSrc)
        .pipe(uglify())
        .pipe(gulp.dest(appDst))
        .pipe(livereload(server));
});

//其他文件拷贝
gulp.task('other', function () {
    var otherSrc = ['./src/fonts/*'],
        otherDst = './dist/fonts/';
    gulp.src(otherSrc)
        .pipe(livereload(server))
        .pipe(gulp.dest(otherDst));
})
// 清空图片、样式、js、字体
gulp.task('clean', function () {
    gulp.src('./dist').pipe(clean());
    // gulp.src(['./dist/css', './dist/js/', './dist/images', './dist/fonts'], {read: false})
    //     .pipe(clean());
});

// 默认任务 清空图片、样式、js并重建 运行语句 gulp
gulp.task('default', ['clean'], function () {
    gulp.start('other', 'css', 'js', 'html', 'images');
});

// 监听任务 运行语句 gulp watch
gulp.task('watch', function () {

    server.listen(port, function (err) {
        if (err) {
            return console.log(err);
        }
        // 监听html
        gulp.watch('./src/*.html', function (event) {
            gulp.run('html');
        })
        // 监听css
        gulp.watch('./src/css/**/*.css', function () {
            gulp.run('css');
        });
        // 监听js
        gulp.watch(['./src/js/**/*.js'], function () {
            gulp.run('js');
        });
    });
});
